<?php

namespace App\Http\Controllers\Api;


use App\Model\Comcheckdetaillog;
use App\Model\Commanager;
use App\Model\Comwordslog;
use Illuminate\Support\Facades\Auth;
use PhpOffice\PhpWord\TemplateProcessor;
use App\Model\Comcheckdetailselflog;
use App\Model\Comcheckgroupself;
use App\Model\Comcheckself;
use App\Model\Comcheckselfstep;
use App\Model\Comwordsselflog;

use App\Http\Controllers\Controller;

use App\Model\Checkgroup;
use App\Model\Checknegative;
use App\Model\Checkaccord;
use App\Model\Checkcommand;
use App\Model\Company;
use App\Model\Comcheck;
use App\Model\Comcheckdetail;
use App\Model\Checkentry;
use App\Model\Comcheckstep;
use App\Model\Comcheckgroup;
use App\Model\Area;
use App\Model\Comsafeofficer;
use App\User;
use App\Services\ImageClass;
use App\Model\Commondata;
use App\Services\Export\WordChoose;

use App\Services\WordcheckdataselfClass;

use Illuminate\Http\Request;
use App\Http\Requests\CheckRequest;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use App\Model\Comcheckdetailself;

class NinecheckselfController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 选择人物环管
     */
    public function choose(Request $request) {
        $status = $request->input('status');
        if($status > 4 || $status < 1) {
            $res_arr["data"] = [];
            $res_arr["code"] = 401;
            $res_arr["message"] = '参数错误';
            return response()->json($res_arr);
        }
        $statusArray = [
            '1'=>'人的不安全行为',
            '2'=>'物的不安全状态',
            '3'=>'作业环境的缺陷',
            '4'=>'安全管理的缺陷',
        ];
        $title = $statusArray[$status];
        $request->session()->put('status',$status);
        $checkId = $request->session()->get('checkId',0);
        $type = $request->session()->get('firetype',0);
        $categoryId = $request->session()->get('categoryId',0);
        $where = ['categoryId'=>$categoryId,'status'=>$status,'type'=>$type];
        $comcheckgroup = new Comcheckgroupself();
        $groups = $comcheckgroup->getCheckgroup($checkId,$categoryId,$status,$type);
        $res_arr['data'] = $groups;
        $res_arr['title'] = $title;
        $res_arr['type'] = $type;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    //新增检查项
    public function creategroup(Request $request)
    {
        $firetype = $request->session()->get('firetype',0);

        $groups = $request->input('group');
        $status = $request->input('status');
        $companyId = $request->session()->get('companyId');
        if(!$firetype || !$companyId) {
            \Session::flash('error', '参数错误!');
            return back();
        }
        $comcheckInfo = Comcheckself::where(['companyId'=>$companyId])->select('id','status')->first();
        if($comcheckInfo) {
            $checkId = $comcheckInfo['id'];
        } else {
            $user = Auth::user();
            $check['companyId'] = $companyId;
            $check['created'] = date('Y-m-d H:i:s',time());
            $check['userId'] = $user->id;
            $checkId = Comcheckself::insertGetId($check);
        }

//        if($groups) {
//            foreach ($groups as $k => $v) {
//                $groups[$k]['checkId'] = $checkId;
//            }
//            Comcheckgroup::insert($groups);
//        }

        $step = [];
        $step['checkId'] = $checkId;
        $step['stepStatus'] = $status;
        $step['typeStatus'] = $firetype;
        $one = Comcheckstep::where(['checkId'=>$step['checkId'],'stepStatus'=>$step['stepStatus'],'typeStatus'=>$step['typeStatus']])->get();
        $one = json_decode(json_encode($one), true);
        if (empty($one)){Comcheckstep::insertGetId($step);}
        $checkStep = Comcheckstep::where(['checkId'=>$checkId,'typeStatus'=>$firetype])->get();
        $stepArray = ['1'=>1,'2'=>2,'3'=>3,'4'=>4];
        foreach ($checkStep as $k => $v) {
            unset($stepArray[$v->stepStatus]);
        }
        if(count($stepArray)) {
            foreach ($stepArray as $k) {
                return redirect('ninecheck/choose/'.$k);
            }
        } else {
            return redirect('ninesmall/choose/'.$firetype);
        }


    }
    //自查 点击检查结束获取文档列表（或签名）
    public function finish(Request $request)
    {
        $companyId = $request->input('companyId');
//        $companyId = 36;
        $fire = 0;
        $nofire = 0;
        $comcheckstep = new Comcheckselfstep();
        $fireinfo = $comcheckstep->getfiretype($companyId);
        if(count($fireinfo)){
            foreach ($fireinfo as $k => $v) {
                if($v->typeStatus == 1) {
                    $fire += $v->stepStatus;
                }
                if($v->typeStatus == 2) {
                    $nofire += $v->stepStatus;
                }
            }
        }
        $company = Company::find($companyId);
        if(!$company) {
            \Session::flash('error', '公司信息有误!');
            return redirect('/ninesmall/firetype/'.$companyId);
        }
        /**新增**/
        $comcheck = new Comcheckself();
        $checkinfo = $comcheck->where(['companyId'=>$companyId])->first();
        $checkdetaillog = Comcheckdetailselflog::where('checkId','=',$checkinfo->id)->orderBy('created_at','desc')->first();
//        $checkdetaillog = json_decode(json_encode($checkdetaillog), true);
//        if (!empty($yes)){
        if (!empty($checkdetaillog->created_at)){
            $yes =strtotime($checkdetaillog->created_at)>($checkinfo->wordsTime)?true:false;
        }else{
            $yes = false;
        }
        $comcheckupdate = Comcheckself::where('id','=',$checkinfo->id)->first();
        if (!empty($comcheckupdate->updated)){
            $insert =$comcheckupdate->updated>($checkinfo->wordsTime)?true:false;
        }else{
            $insert = false;
        }
        if (!$yes && !$insert)
        {
            $yess = true;
        }else{
            $yess = false;

        }
        /**新增**/
        if($company['schedule'] >= 2 && $yess) {
            if (empty($companyId)){
                $res_arr["data"] = [];
                $res_arr["code"] = 401;
                $res_arr["message"] = '参数错误';
                return response()->json($res_arr);
            }
            $comcheck = new Comcheckself();
            $comCheckdetail = new Comcheckdetailself();
            $checkinfo = $comcheck->where(['companyId'=>$companyId])->first();
            $download = [];
            $wordsUrl = $checkinfo->wordsUrl;
            $checkdetaillog = Comcheckdetailselflog::where('checkId','=',$checkinfo->id)->orderBy('created_at','desc')->first();

            if (!empty($checkdetaillog->created_at)){
                $yes =strtotime($checkdetaillog->created_at)>($checkinfo->wordsTime)?true:false;
            }else{
                $yes = false;
            }
            $urlArray = explode(',', $wordsUrl);
            foreach ($urlArray as $k => $v) {
                $download[$k]['name'] = substr(strrchr($v,'/'),1,-16);
                $download[$k]['url'] = substr($v,1);
                $download[$k]['pdfurl']= substr($download[$k]['url'],0,strlen($download[$k]['url'])-4).'pdf';
            }
            $res_arr['data']['downloadlist'] = $download;

        }
        //获取初查隐患
        $detail = new Comcheckdetailself();
//        dd($checkinfo->id);da'te'post
//        $comcheck = Comcheck::find($id);
        $infos = $detail->getInconform($checkinfo->id);
        $negatives = [];
        foreach ($infos as $k=>$v){
            if (!empty($v->negatives)){
                $arr = explode(',',$v->negatives);
                foreach ($arr as $ar){
                    if (!empty($ar)){
                        array_push($negatives,$ar);
                    }
                }
            }
        }
        $negatives = Checknegative::whereIn('id',$negatives)->get();
        $res_arr['data']['negatives'] = $negatives;
        $res_arr['data']['type'] = 2;
        $res_arr['data']['companyId'] = $companyId;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     * 查看风险点
     */
    public function show(Request $request) {
        $groupId = $request->input('groupId');
        $groupInfo = Checkgroup::find($groupId);
        if(empty($groupInfo)){
            return back();
        }
        $is = $groupInfo->status;
        $type = $groupInfo->type;
        $title = $groupInfo->name;
        $accidentType = $groupInfo->accidentType;

        $entrys = Checkentry::where('groupId',$groupId)->get();
        $res_arr['data']['entrys'] = $entrys;
        $res_arr['data']['accidentType'] = $accidentType;
        $res_arr['data']['is'] = $is;
        $res_arr['data']['type'] = $type;

        $res_arr['data']['title'] = $title;
        $res_arr['data']['groupId'] = $groupId;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 查看其他
     */
    public function showelse(Request $request) {
        $groupId = $request->input('groupId');
        $groupInfo = Checkgroup::find($groupId);

        if(empty($groupInfo)){
            $res_arr["data"] = [];
            $res_arr["code"] = 401;
            $res_arr["message"] = '参数错误';
            return response()->json($res_arr);
            return response()->json($res_arr);
        }
        $title = $groupInfo->name;
        $entrys = Checkentry::where('groupId',$groupId)->get();
        $res_arr['data'] = $entrys;
        $res_arr['title'] = $title;
        $res_arr['groupId'] = $groupId;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }


    //检查项的提交
    public function create(CheckRequest $request) {
        $data = $request->input();
        $groupId = $data['groupId'];
        $checkId = $data['checkId'];
        $statuss = $data['statuss'];
        if(!$checkId)
        {
            $res_arr["data"] = [];
            $res_arr["code"] = 401;
            $res_arr["message"] = '参数错误';
            return response()->json($res_arr);
        }
        $dangers = $data['dangers'];
        $insert = [];
        /*$dangers = [[
            'entryId'=>'2',
            'status'=>'1',
            'contentexist'=>'安全出口保持畅通无阻，禁止上锁、堵塞。',
            'isfire'=>'1',
            'content'=>['未依法明确消防安全责任人、管理人及其职责的','未依法明确消防安全责任人、管理人及其职责的'],
            'picture'=>['sfds','eee'],
            'negatives'=>['安全出口保持畅通无阻','禁止上锁、堵塞'],
            'checkId'=>'1',
            'groupId'=>'84',
            ]];*/
        foreach ($dangers as $key=>$va){

            $insert[$key]['entryId'] = $va['entryId'];
            $insert[$key]['status'] = $va['status'];
            if (!empty($va['contentexist'])){
                $insert[$key]['status'] = 2;
            }
            $insert[$key]['isfire'] = $va['isfire'];
            if(!empty($va['content'])){
                $str = '';
                foreach ($va['content'] as $va1){
                     $str .= $va1;
                     $str .= ';';
                }
                $insert[$key]['content'] = $str;
            }else{
                $insert[$key]['content'] = '';
            }
            if(!empty($va['contentexist'])){
                $insert[$key]['contentexist'] = $va['contentexist'];
            }
            if (!empty($va['picture'])){
                $insert[$key]['pictures'] = implode(",", $va['picture']);
            }
            if (!empty($va['negatives'])){
                $insert[$key]['negatives'] = implode(",", $va['negatives']);
            }
            $insert[$key]['checkId'] = $checkId;
            $insert[$key]['groupId'] = $groupId;
        }

        $firetype = Checkgroup::find($groupId)->type;

        $comCheckdetail = new Comcheckdetailself();
        foreach ($insert as $k=>$v){
            if($v['isfire'] == 0){
                $one = Comcheckdetailself::where(['checkId'=>$v['checkId'],'groupId'=>$v['groupId'],'entryId'=>$v['entryId']])->get();
                $one = json_decode(json_encode($one), true);
                if (empty($one)){
                    Comcheckdetailself::insert($v);}
            }else{
                Comcheckdetailself::insert($v);
            }
        }
        Comcheckself::where('id','=',$checkId)->update(['updated'=>time()]);
        $step = [];
        $step['checkId'] = $checkId;
        $step['stepStatus'] = $statuss;
        $step['typeStatus'] = $firetype;
        $one = Comcheckselfstep::where(['checkId'=>$step['checkId'],'stepStatus'=>$step['stepStatus'],'typeStatus'=>$step['typeStatus']])->get();
        $one = json_decode(json_encode($one), true);
        if (empty($one)){Comcheckselfstep::insertGetId($step);}
        $res_arr["data"] = [];
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }


    /**
     * @param CheckRequest $request
     * @return \Illuminate\Http\JsonResponse
     * 其他检查项的提交
     */
    public function createelse(CheckRequest $request) {
        $data = $request->input();
        $groupId = $request->input('groupId');
        $checkId = $request->session()->get('checkId',0);
        $status = $request->session()->get('status',0);
        $contents = $data['content'];
        $pictures = is_array($data['picture'])?$data['picture']:0;
        foreach ($contents as $k => $v) {
            $checkdetail[$k]['checkId'] = $checkId;
            $checkdetail[$k]['groupId'] = $groupId;
            $checkdetail[$k]['content'] = $v;
            if (empty($v)){
                $checkdetail[$k]['status'] = 1;
            }else{
                $checkdetail[$k]['status'] = 2;
            }
        }
        if($pictures) {
            foreach ($pictures as $k => $v) {
                $checkdetail[$k]['pictures'] = $v;
            }
        }
        $checkgroup['checkId'] = $checkId;
        $checkgroup['groupId'] = $groupId;
        $checkgroup['status'] = 1;
        /*使用事务插入*/
        DB::beginTransaction();
        try{
            $insert = Comcheckgroupself::insertGetId($checkgroup);
            if($insert) {
                DB::commit();
            }
        }catch (\Exception $e) {
            DB::rollBack();
            $res_arr["code"] = 402;
            $res_arr["message"] = '请勿重复提交结果';
            return response()->json($res_arr);
        }
        $comCheckdetail = new Comcheckdetailself();
        $comCheckdetail->addAll($checkdetail);
        // $this->exportWord1($checkId);
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    // 自查 隐患修改
    public function update(Request $request){
        $data = $request->input();
        $groupId = $data['groupId'];
        $checkId = $data['checkId'];
        $data = Comcheckdetailself::where(['checkId'=>$checkId,'groupId'=>$groupId])->get();
        $data = json_decode(json_encode($data), true);

        $negatives = [];
        foreach ($data as $v){
            if (!empty($v['negatives'])){
            $arr = explode(",",$v['negatives']);
            foreach ($arr as $v1){
                empty($v1)?'':array_push($negatives,$v1);
            }}
        }
        if(!empty($negatives)){
            $negativess = Checknegative::whereIn('id',$negatives)->get();
        }else{
            $negativess = [];
        }

        $groupInfo = Checkgroup::find($groupId);
        if(empty($groupInfo)){
//            return back();
        }
        $comcheckgroup = [];
        $comcheckgroup = Comcheckgroupself::where(['checkId'=>$checkId,'groupId'=>$groupId])->first();
        $entrys = Checkentry::where('groupId',$groupId)->get();
        $title = $groupInfo->name;
        $type = $groupInfo->type;
        $datas = [];
        foreach ($data as $da){
            $dataone = [];
            $dataone['id'] = $da['id'];
            $dataone['checkId'] = $da['checkId'];
            $dataone['groupId'] = $da['groupId'];
            $dataone['entryId'] = $da['entryId'];
            $dataone['status'] = $da['status'];
            $dataone['negativearr'] = [];
            if (!empty($da['negatives'])){
                $dataone['negatives'] = explode(',',$da['negatives']);
            }else{
                $dataone['negatives'] = [];
            }
            foreach ($dataone['negatives'] as $ke=>$val){
                foreach ($negativess as $ne){
                    if ($ne['id'] == $val){
                        array_push($dataone['negativearr'],$ne);
                    }
                }
            }
            if (!empty($da['content'])){
                $dataone['content'] = explode(';',$da['content']);
            }else{
                $dataone['content'] = [];
            }
            if (!empty($da['pictures'])){
                $dataone['pictures'] = explode(',',$da['pictures']);
            }else{
                $dataone['pictures'] = [];
            }
            if (!empty($da['video'])){
                $dataone['video'] = explode(',',$da['video']);
            }else{
                $dataone['video'] = [];
            }
            $dataone['contentexist'] = $da['contentexist'];
            $dataone['isfire'] = $da['isfire'];

            array_push($datas,$dataone);
        }
        $res_arr1['data'] = $datas;
        $res_arr1['groupId'] = $groupId;
        $res_arr1['entrys'] = $entrys;
        $res_arr1['comcheckgroup'] = $comcheckgroup;
        $res_arr1['negatives'] = $negativess;
        $res_arr1['title'] = $title;
        $res_arr1['type'] = $type;
        $res_arr['data'] = $res_arr1;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);

    }
    public function updateelse(Request $request,int $groupId){
        $checkId = $request->session()->get('checkId',0);
        $data = Comcheckdetailself::where(['checkId'=>$checkId,'groupId'=>$groupId])->get();
//        $data = json_decode(json_encode($data), true);
//        dd($data);
        $negatives = [];
        foreach ($data as $v){
            $arr = explode(",",$v->negatives);
            foreach ($arr as $v1){
                empty($v1)?'':array_push($negatives,$v1);
            }
        }
        $negatives = Checknegative::whereIn('id',$negatives)->get();

        $groupInfo = Checkgroup::find($groupId);
        if(empty($groupInfo)){
            return back();
        }
        $comcheckgroup = [];
        $comcheckgroup = Comcheckgroupself::where(['checkId'=>$checkId,'groupId'=>$groupId])->first();
        $entrys = Checkentry::where('groupId',$groupId)->get();
        $title = $groupInfo->name;
        $ren= $comcheckgroup->ren;$caichan=$comcheckgroup->cai;$des = $comcheckgroup->des;
        return view('ninecheck/updateelse')
            ->with('data',$data)
            ->with('groupId',$groupId)
            ->with('entrys',$entrys)
            ->with('ren',$ren)
            ->with('caichan',$caichan)
            ->with('des',$des)
            ->with('comcheckgroup',$comcheckgroup)
            ->with('negatives',$negatives)
            ->with('title',$title);

    }
    public function updatepost(Request $request){
        $data = $request->all();
        $groupId = $data['groupId'];
        $firetype = Checkgroup::find($groupId)->type;
        $checkId = $data['checkId'];
        if(!$checkId)
        {
//            return redirect('/ninesmall');
        }
        $dangers = $data['dangers'];
        $update = [];
        /*$dangers = [[
            'id'=>'1',
            'entryId'=>'2',
            'status'=>'2',
            'contentexist'=>'安全出口保持畅通无阻，禁止上锁、堵塞3。',
            'isfire'=>'4',
            'content'=>['未依法明确消防安全责任人、管理人及其职责的3','未依法明确消防安全责任人、管理人及其职责的5'],
            'picture'=>['sfds1','eee1'],
            'negatives'=>['安全出口保持畅通无阻','禁止上锁、堵塞2'],
            'checkId'=>'2',
            'groupId'=>'84',
        ]];*/
        foreach ($dangers as $key=>$va){
            $update[$key]['id'] = $va['id'];
            $update[$key]['entryId'] = $va['entryId'];
            $update[$key]['status'] = $va['status'];
            if (empty($va['contentexist']) && empty($va['entryId'])){
                $update[$key]['status'] = 1;
            }
            if (!empty($va['contentexist']) && empty($va['entryId'])){
                $update[$key]['status'] = 2;
            }

            if(!empty($va['content'])){
                $str = '';
                foreach ($va['content'] as $va1){
                    $str .= $va1;
                    $str .= ';';
                }
                $update[$key]['content'] = $str;
            }else{
                $update[$key]['content'] = '';
            }

            if(!empty($va['contentexist'])) {
                $update[$key]['contentexist'] = $va['contentexist'];
            }

//            if (empty($va['picture'])){
//                $detail = Comcheckdetail::where('id','=',$va['id'])->get();
//                $detail = json_decode(json_encode($detail), true);
//                $update[$key]['pictures'] = $detail[0]['pictures'];
//            }else{
                $update[$key]['pictures'] = implode(",", $va['picture']);
//            }

            if (!empty($va['negatives'])){
                $update[$key]['negatives'] = implode(",", $va['negatives']);
            }
            $update[$key]['checkId'] = $checkId;
            $update[$key]['groupId'] = $groupId;
        }
        Comcheckself::where('id','=',$checkId)->update(['updated'=>time()]);
        $time = time();
        foreach ($update as $v){
            if(empty($v['id'])){
                unset($v['id']);
                Comcheckdetailself::insert($v);
            }else{
            $result = Comcheckdetailself::where('id','=',$v['id'])->update($v);
            $old = Comcheckdetailself::where('id','=',$v['id'])->get();
            $old = json_decode(json_encode($old), true);
            $old[0]['created_at'] = $time;
            $comCheckdetaillog = new Comcheckdetailselflog();
            $comCheckdetaillog->addAll($old[0]);
            }
        }
        $res_arr["data"] = $data;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }


    public function updateelsepost(Request $request){
        $data = $request->all();
        $groupId = $request->input('groupId');
        $ids = $request->input('id');
        $checkId = $request->session()->get('checkId',0);
        $status = $request->session()->get('status',0);
        $contents = $data['content'];
        $pictures = is_array($data['picture'])?$data['picture']:0;
        foreach ($contents as $k => $v) {
            $checkdetail[$k]['checkId'] = $checkId;
            $checkdetail[$k]['id'] = $ids[$k];
            $checkdetail[$k]['groupId'] = $groupId;
            $checkdetail[$k]['content'] = $v;
            if (empty($v)){
                $checkdetail[$k]['status'] = 1;
            }else{
                $checkdetail[$k]['status'] = 2;
            }
        }
        if($pictures) {
            foreach ($pictures as $k => $v) {
                if (empty($v)){
                    $detail = Comcheckdetailself::where('id','=',$ids[$k])->get();
                    $detail = json_decode(json_encode($detail), true);
                    $checkdetail[$k]['pictures'] = $detail[0]['pictures'];
                }else{
                    $checkdetail[$k]['pictures'] = $v;
                }
            }
        }
        Comcheck::where('id','=',$checkId)->update(['updated'=>time()]);
        $time = time();
        foreach ($checkdetail as $v){
            $result = Comcheckdetailself::where('id','=',$v['id'])->update($v);
            $old = Comcheckdetailself::where('id','=',$v['id'])->get();
            $old = json_decode(json_encode($old), true);
            $old[0]['created_at'] = $time;
            $comCheckdetaillog = new Comcheckdetailselflog();
            $comCheckdetaillog->addAll($old[0]);
        }
        return redirect('ninecheck/choose/'.$status);
    }

    /**
     * 签名提交生成文档
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function signature(Request $request)
    {
        $companyId = $request->input('companyId');
        $againDate = $request->input('againDate')?:'2023-10-21';
        $comcheckInfo = Comcheckself::where(['companyId'=>$companyId])->select('id','status')->first();
        $company = Company::find($companyId);
        $companyName = $company->comName;
        //        if(!$comcheckInfo) {
//            $res_arr["data"] = [];
//            $res_arr["code"] = 401;
//            $res_arr["message"] = '参数错误';
//            return response()->json($res_arr);
//        }
        $lng = $company->lng;
        $lat = $company->lat;
        $userimgbase=$request->input('userimgbase');
        $comimgbase=$request->input('comimgbase');
        if(empty($userimgbase)) {
            $res_arr["data"] = [];
            $res_arr["code"] = 407;
            $res_arr["message"] = '未签名';
            return response()->json($res_arr);
        }
        $imgclass = new ImageClass();
        $usersignature = $userimgbase;
        $comsignature = $comimgbase;
        //$mapimg = $imgclass->maptoimg($lng,$lat,$companyName);
        $mapimg = '';
        $update = [
            'comsignature'=>$comsignature,
            'usersignature'=>$usersignature,
            'lng'=>$lng,
            'lat'=>$lat,
            'mapimg'=>$mapimg,
            'updated'=>time(),
            'againDate'=>$againDate
        ];
        Comcheckself::where(['companyId'=>$companyId])->update($update);
        $wancheng = Company::where(['id'=>$companyId])->first();
        if ($wancheng->schedule >=2){

        }else{
            Company::where(['id'=>$companyId])->update(['schedule'=>2]);
        }
        self::download($companyId);


    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 点击文档按钮
     */
    public function downloadwords(Request $request)
    {
        $companyId = $request->input('companyId');
        if (empty($companyId)){
            $res_arr["data"] = [];
            $res_arr["code"] = 401;
            $res_arr["message"] = '参数错误';
            return response()->json($res_arr);
        }
        $comcheck = new Comcheckself();
        $comCheckdetail = new Comcheckdetailself();
        $checkinfo = $comcheck->where(['companyId'=>$companyId])->first();
        $download = [];
        $wordsUrl = $checkinfo->wordsUrl;
        $checkdetaillog = Comcheckdetailselflog::where('checkId','=',$checkinfo->id)->orderBy('created_at','desc')->first();

        if (!empty($checkdetaillog->created_at)){
            $yes =strtotime($checkdetaillog->created_at)>($checkinfo->wordsTime)?true:false;
        }else{
            $yes = false;
        }
//        if(!$wordsUrl || $yes) {
//            $wordsUrl = $this->exportWord($companyId);
//            /***新增***/
//            $checkinfo->wordsUrl = $wordsUrl;
//            $checkinfo->wordsTime = time();
//
//            /***新增***/
//            $checkinfo->save();
//            $log = [];
//            $log['checkId'] = $checkinfo->id;
//            $log['wordUrl'] = $checkinfo->wordsUrl;
//            $log['comsignature'] = $checkinfo->comsignature;
//            $log['usersignature'] = $checkinfo->usersignature;
//            $log['created'] = time();
//            $result = Comwordslog::insert($log);
//        }
        $urlArray = explode(',', $wordsUrl);
        foreach ($urlArray as $k => $v) {
            $download[$k]['name'] = substr(strrchr($v,'/'),1,-16);
            $download[$k]['url'] = substr($v,1);
        }
        $res_arr['data'] = $download;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    public static function download($companyId)
    {
	    // $wordsUrl = $this->exportWord($companyId);
        $comcheck = new Comcheckself();
        $comCheckdetail = new Comcheckdetailself();
        $checkinfo = $comcheck->where(['companyId'=>$companyId])->first();
        $download = [];
        $wordsUrl = $checkinfo->wordsUrl??'';
        $checkdetaillog = Comcheckdetailselflog::where('checkId','=',$checkinfo->id)->orderBy('created_at','desc')->first();

        if (!empty($checkdetaillog->created_at)){
            $yes =strtotime($checkdetaillog->created_at)>($checkinfo->wordsTime)?true:false;
        }else{
            $yes = false;
        }
        $comcheckupdate = Comcheckself::where('id','=',$checkinfo->id)->first();
        if (!empty($comcheckupdate->updated)){
            $insert =$comcheckupdate->updated>($checkinfo->wordsTime)?true:false;
        }else{
            $insert = false;
        }
        if ($yes || $insert)
        {
            $yess = true;
        }else{
            $yess = false;

        }


//        dd($yess);
        if(!$wordsUrl || $yess) {
            $wordsUrl = self::exportWordSelf($companyId);
            /***新增***/
            $checkinfo->wordsUrl = $wordsUrl;
            $checkinfo->wordsTime = time();

            /***新增***/
            $checkinfo->save();
            $log = [];
            $log['checkId'] = $checkinfo->id;
            $log['wordUrl'] = $checkinfo->wordsUrl;
            $log['comsignature'] = $checkinfo->comsignature;
            $log['usersignature'] = $checkinfo->usersignature;
            $log['created'] = time();
            $result = Comwordsselflog::insert($log);
        }

        $urlArray = explode(',', $wordsUrl);
        foreach ($urlArray as $k => $v) {
            $download[$k]['name'] = substr(strrchr($v,'/'),1,-16);
            $download[$k]['url'] = substr($v,1);
        }
        $res_arr['data'] = $download;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        echo json_encode($res_arr);
        exit();
    }

    /**
     * 生成检测报告
     *
     **/
    protected static function exportWord($companyId)
    {
        $company = Company::find($companyId);
        /*主要负责人*/
        $manager = Commanager::where('companyId', $company->id)->first();
        /*安全负责人*/
        $safeUser = Comsafeofficer::where('companyId', $company->id)->first();
        //检查情况
        $comcheck = new Comcheckself();
        $checkinfo = $comcheck->where(['companyId'=>$companyId])->first();
        /*初查检查人员*/
        $checkUser = User::where('id', $checkinfo->userId)->first();
        //负面清单
        $comCheckdetail = new Comcheckdetailself();
        $checkdetail = $comCheckdetail->getCheckDetail($companyId);
        //法律依据
        $accordObj = new Checkaccord();
        $checkAccords = $accordObj->getAccordByCheckId($checkinfo->id);

        $comName = $company->comName;
        $created = date('Ymdhi',strtotime($checkinfo->created));
        $address = [];
        $address['province'] = Area::find($company->province)->name;
        $address['city'] = Area::find($company->city)->name;
        $address['district'] = Area::find($company->district)->name;
        $address['street'] = Area::find($company->street)->name;

        //数据整理
        $checkDataClass = new WordcheckdataClass();
        $wordData = $checkDataClass->createNotice($company,$checkinfo,$checkdetail,$address,$checkUser,$manager);
        $fireData = $wordData['data'];
        $fireData = array_merge($fireData,$wordData['fire']);
        $imgData = $wordData['imgData'];
        $productData = $wordData['data'];
        $productData = array_merge($productData, $wordData['product']);
        //生成隐患告知单
        $fireTemplateProcessor =  new TemplateProcessor('./word/消防安全事故隐患告知单-初查.docx');
        $unfireTemplateProcessor = new TemplateProcessor('./word/生产安全事故隐患告知单-初查.docx');
        $fireDocName = $comName.'消防安全事故隐患告知单_' . $created;
        $unfireDocName = $comName.'生产安全事故隐患告知单_' . $created;
        $fireWordClass = WordChoose::choose($fireTemplateProcessor,'notice');
        $unfireWordClass = WordChoose::choose($unfireTemplateProcessor,'notice');
        $fireWordClass->set($fireData,$imgData);
        $unfireWordClass->set($productData, $imgData);
        $fireNoticeUrl = $fireWordClass->create(date('Ymd', time()),$fireDocName);
        $unfireNoticeUrl = $unfireWordClass->create(date('Ymd', time()), $unfireDocName);
        //检查表
        $fireCheckProcessor =  new TemplateProcessor('./word/消防安全检查记录表-初查.docx');
        $unfireCheckProcessor = new TemplateProcessor('./word/生产安全检查记录表-初查.docx');
        $fireDocName = $comName.'消防安全检查记录表_' . $created;
        $unfireDocName = $comName.'生产安全检查记录表_' . $created;
        /*导出word*/
        $exportData = $checkDataClass->createRecord($company,$checkinfo,$checkdetail,$checkUser, $address, $safeUser,$checkAccords);

        $exportFireBasicData = $exportData['exportLogData'];
        $exportFireBasicData = array_merge($exportFireBasicData, $exportData['exportFireNum']);
        $exportFireLogData = $exportData['exportFireLogData'];

        $exportUnFireBasicData = $exportData['exportLogData'];
        $exportUnFireBasicData = array_merge($exportUnFireBasicData, $exportData['exportUnfireNum']);
        $exportUnFireLogData = $exportData['exportUnFireLogData'];

        $fireWordClass = WordChoose::choose($fireCheckProcessor,'nineCheckAgainLog');
        $fireWordClass->set($exportFireBasicData, $exportFireLogData);
        $fireWordUrl = $fireWordClass->create(date('Ymd', time()),$fireDocName);
        $unfireWordClass = WordChoose::choose($unfireCheckProcessor,'nineCheckAgainLog');
        $unfireWordClass->set($exportUnFireBasicData, $exportUnFireLogData);
        $unfireWordUrl = $unfireWordClass->create(date('Ymd', time()),$unfireDocName);

        /*生成基础档案*/

        $checkDataClass = new WordcheckdataClass();
        $archivesWordData = $checkDataClass->createArchives($company,$safeUser,$manager,$address,$checkinfo,$checkdetail,$checkUser,$checkAccords);
        $returnImg = $checkDataClass->generateImg($checkdetail);
        $archivesWordData['imgData'] = array_merge($archivesWordData['imgData'], $returnImg);
        $archivesProcessor =  new TemplateProcessor('./word/安全检查档案-初查.docx');
        $archivesDocName = $comName.'安全检查档案_' . $created;
        $archivesWordClass = WordChoose::choose($archivesProcessor,'archives');
        $archivesWordClass->set($archivesWordData['basicData'], $archivesWordData['imgData'], $archivesWordData['record']);
        $archivesWordUrl = $archivesWordClass->create(date('Ymd', time()),$archivesDocName);



        /*保存word文档路径*/
        $checkinfo->wordsUrl = $fireNoticeUrl.','.$unfireNoticeUrl.','.$fireWordUrl.','.$unfireWordUrl.','.$archivesWordUrl;

        return $checkinfo->wordsUrl;
    }

    public function checkdelete(Request $request){
        $data = $request->all();
        $id = $data['id'];
        $result  = DB::delete('delete from comcheckdetail where id = ?',[$id]);
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        echo json_encode($res_arr);
        exit();
    }


    /**
     * 生成检测报告
     *
     **/
    protected static function exportWordSelf($companyId)
    {
        $company = Company::find($companyId);
        /*主要负责人*/
        $manager = Commanager::where('companyId', $company->id)->first();
        /*安全负责人*/
        $safeUser = Comsafeofficer::where('companyId', $company->id)->first();
        //检查情况
        $comcheck = new Comcheckself();
        $checkinfo = $comcheck->where(['companyId'=>$companyId])->first();
        /*初查检查人员*/
        $checkUser = User::where('id', $checkinfo->userId)->first();
        //负面清单
        $comCheckdetail = new Comcheckdetailself();
        $checkdetail = $comCheckdetail->getCheckDetail($companyId);
        //法律依据
        $accordObj = new Checkaccord();
        $checkAccords = $accordObj->getAccordByCheckId($checkinfo->id);

        $comName = $company->comName;
        $created = time(); //date('Ymdhi',strtotime($checkinfo->created))
        $address = [];
        $address['province'] = '';
        $address['city'] = '';
        $address['district'] = '';
        $address['street'] = '';
        try{
            $address['province'] = Area::find($company->province)->name;
            $address['city'] = Area::find($company->city)->name;
            $address['district'] = Area::find($company->district)->name;
            $address['street'] = Area::find($company->street)->name;
        } catch (\Exception $e) {

        }

        if($company->enterprise==3){
            // 住户类型
            //数据整理
            $checkDataClass = new WordcheckdataselfClass();
            $wordData = $checkDataClass->createNoticeSelf($company,$checkinfo,$checkdetail,$address,$checkUser,$manager);
            $fireData = $wordData['data'];
            // dd($wordData);
            $firedata = [];
            $wordData['fire']['manageArchive'] = $wordData['fire']['manageArchive'].$wordData['product']['manageArchive'];
            $wordData['fire']['work'] = $wordData['fire']['work'].$wordData['product']['work'];
            $fireData = array_merge($fireData,$wordData['fire']);
            // $fireData = array_merge($fireData,$wordData['product']);
            $imgData = $wordData['imgData'];
            //生成隐患告知单
            $fireTemplateProcessor =  new TemplateProcessor('./word/住户安全事故隐患告知单-初查.docx');
            $fireDocName = $comName.'住户安全检查告知单_' . $created;
            $fireWordClass = WordChoose::choose($fireTemplateProcessor,'notice');
            $fireWordClass->set($fireData,$imgData);
            $fireNoticeUrl = $fireWordClass->create(date('Ymd', time()),$fireDocName);
            // //检查表
            $fireCheckProcessor =  new TemplateProcessor('./word/住户安全检查记录表-初查.docx');
            $fireDocName = $comName.'住户安全检查记录表_' . $created;
            /*导出word*/
            $exportData = $checkDataClass->createRecordSelf($company,$checkinfo,$checkdetail,$checkUser, $address, $safeUser,$checkAccords);

            $exportFireBasicData = $exportData['exportLogData'];
            $exportFireBasicData = array_merge($exportFireBasicData, $exportData['exportFireNum']);
            $exportFireLogData = $exportData['exportFireLogData'];
            $exportUnFireBasicData = $exportData['exportLogData'];
            $exportUnFireBasicData = array_merge($exportUnFireBasicData, $exportData['exportUnfireNum']);
            $exportUnFireLogData = $exportData['exportUnFireLogData'];
            $exportFireLogData = array_merge($exportFireLogData,$exportUnFireLogData);
            $j = 1;
            $exportFireLogDatanew = [];
            foreach($exportFireLogData as $k) {
                $exportFireLogDatanew[$j] = $k;
                $exportFireLogDatanew[$j]['num'] = $j;
                $j++;
            }
            $fireWordClass = WordChoose::choose($fireCheckProcessor,'nineCheckAgainLog');
            $fireWordClass->set($exportFireBasicData, $exportFireLogDatanew);
            $fireWordUrl = $fireWordClass->create(date('Ymd', time()),$fireDocName);

            /*保存word文档路径*/
            $checkinfo->wordsUrl = $fireNoticeUrl.','.$fireWordUrl;
            return $checkinfo->wordsUrl;
        }else{
            // 其他
            //数据整理
            $checkDataClass = new WordcheckdataselfClass();
            //生成隐患告知单数据
            $wordData = $checkDataClass->createNoticeSelf($company,$checkinfo,$checkdetail,$address,$checkUser,$manager);
            $fireData = $wordData['data'];
            $fireData = array_merge($fireData,$wordData['fire']);
            $imgData = $wordData['imgData'];
            $productData = $wordData['data'];
            $productData = array_merge($productData, $wordData['product']);
            //生成隐患告知单
            $fireTemplateProcessor =  new TemplateProcessor('./word/消防安全事故隐患告知单-初查.docx');
            $unfireTemplateProcessor = new TemplateProcessor('./word/生产安全事故隐患告知单-初查.docx');
            $fireDocName = $comName.'消防安全检查告知单_' . $created;
            $unfireDocName = $comName.'生产安全检查告知单_' . $created;
            $fireWordClass = WordChoose::choose($fireTemplateProcessor,'notice');
            $unfireWordClass = WordChoose::choose($unfireTemplateProcessor,'notice');
            $fireWordClass->set($fireData,$imgData);
            $unfireWordClass->set($productData, $imgData);
            $fireNoticeUrl = $fireWordClass->create(date('Ymd', time()),$fireDocName);
            $unfireNoticeUrl = $unfireWordClass->create(date('Ymd', time()), $unfireDocName);
            //检查表
            $fireCheckProcessor =  new TemplateProcessor('./word/消防安全检查记录表-初查.docx');
            $unfireCheckProcessor = new TemplateProcessor('./word/生产安全检查记录表-初查.docx');
            $fireDocName = $comName.'消防安全检查记录表_' . $created;
            $unfireDocName = $comName.'生产安全检查记录表_' . $created;
            /*导出word*/
            $exportData = $checkDataClass->createRecordSelf($company,$checkinfo,$checkdetail,$checkUser, $address, $safeUser,$checkAccords);

            $exportFireBasicData = $exportData['exportLogData'];
            $exportFireBasicData = array_merge($exportFireBasicData, $exportData['exportFireNum']);
            $exportFireLogData = $exportData['exportFireLogData'];

            $exportUnFireBasicData = $exportData['exportLogData'];
            $exportUnFireBasicData = array_merge($exportUnFireBasicData, $exportData['exportUnfireNum']);
            $exportUnFireLogData = $exportData['exportUnFireLogData'];

            $fireWordClass = WordChoose::choose($fireCheckProcessor,'nineCheckAgainLog');
            $fireWordClass->set($exportFireBasicData, $exportFireLogData);
            $fireWordUrl = $fireWordClass->create(date('Ymd', time()),$fireDocName);
            $unfireWordClass = WordChoose::choose($unfireCheckProcessor,'nineCheckAgainLog');
            $unfireWordClass->set($exportUnFireBasicData, $exportUnFireLogData);
            $unfireWordUrl = $unfireWordClass->create(date('Ymd', time()),$unfireDocName);

            /*生成基础档案*/

            $checkDataClass = new WordcheckdataselfClass();
            $archivesWordData = $checkDataClass->createArchives($company,$safeUser,$manager,$address,$checkinfo,$checkdetail,$checkUser,$checkAccords);
            $returnImg = $checkDataClass->generateImg($checkdetail);
            $archivesWordData['imgData'] = array_merge($archivesWordData['imgData'], $returnImg);
            $archivesProcessor =  new TemplateProcessor('./word/安全检查档案-初查.docx');
            $archivesDocName = $comName.'安全检查档案_' . $created;
            $archivesWordClass = WordChoose::choose($archivesProcessor,'archives');
            $archivesWordClass->set($archivesWordData['basicData'], $archivesWordData['imgData'], $archivesWordData['record']);
            $archivesWordUrl = $archivesWordClass->create(date('Ymd', time()),$archivesDocName);
            /*保存word文档路径*/
            $checkinfo->wordsUrl = $fireNoticeUrl.','.$unfireNoticeUrl.','.$fireWordUrl.','.$unfireWordUrl.','.$archivesWordUrl;
            return $checkinfo->wordsUrl;
        }

    }
}
